﻿namespace CookieTerm
{
	using System;
	using Gtk;

    public class MultiTab : Box
    {
        public Label Caption;
        Image img = new Image("C:\\Users\\deren\\Documents\\cookieTerm.svn\\CookieTerm.WinForm\\UILogic\\MdiTabStrip\\Resources\\Document.ico");
        public ToolButton Close;
        public Notebook _parent;

        public MultiTab ( string name )
        {
            CreateUI(name);
        }

        public MultiTab(string name, Notebook parent)
        {
            _parent = parent;
            CreateUI(name);
            CreateHandlers();
        }

        void CreateUI(string name)
        {
            Caption = new Gtk.Label(name);
            Close = new Gtk.ToolButton(img,"");
            PackStart( Caption );
            PackStart( Close );
            ShowAll();
            //Close.Hide();
        }

        void CreateHandlers()
        {
            Close.Clicked +=  delegate {
                    _parent.RemovePage(_parent.CurrentPage);
                };
        }
    }    

	public partial class MainWindow: Gtk.Window
	{
		private BookmarkManager bookmarkManager;

		public MainWindow () : base (Gtk.WindowType.Toplevel)
		{
			Build ();

			this.bookmarkManager = new BookmarkManager();
			this.bookmarkManager.Load();

			LoadBookmarkMenu();
		}

		protected void OnDeleteEvent (object sender, DeleteEventArgs a)
		{
			Application.Quit ();
			a.RetVal = true;
		}

		private void LoadBookmarkMenu ()
		{
			MenuItem openMenuItem = (MenuItem)this.UIManager.GetWidget ("/mainMenuBar/BookmarkAction/OpenAction");
			if (openMenuItem == null) 
			{
				throw new InvalidOperationException ("Cannot find Bookmark -> Edit menu item.");
			}

            Menu openSubMenu = new Menu();
            openMenuItem.Submenu = openSubMenu;

            for (int i = 0; i < this.bookmarkManager.Bookmarks.Count; i++)
            {
                string text = (i < 10 ? "_" : "") + i + " " + this.bookmarkManager.Bookmarks[i].Name;
                MenuItem item = new MenuItem(text);
                item.Name = this.bookmarkManager.Bookmarks[i].Name;
                item.Activated += this.OnBookmarkClicked;

                #if false
				if (i < 10) 
				{
					item.ShortcutKeys = Keys.Control | Keys.Alt | (Keys.D0 + i);
				}
				item.Click += new EventHandler (BookmarkClick);
                #endif
                openSubMenu.Append(item);
            }

			ShowAll ();
		}

		protected void OnManageMenuItemClicked (object sender, EventArgs e)
		{
            throw new NotImplementedException ();
		}

		protected void OnBookmarkClicked (object sender, EventArgs e)
        {
            MenuItem item = (MenuItem)sender;
            Bookmark bookmark = this.bookmarkManager.FindBookmark(item.Name);

            Label w = new Label();

            MultiTab tabLabel = new MultiTab(bookmark.Name, this.notebook);
            this.notebook.AppendPage(w, tabLabel);
            w.Show();
        }
	}
}